<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    name="normal_login"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-tabs
      v-model:activeKey="activeKey"
      :tabBarStyle="{
        textAlign: 'center !important',
        borderBottom: 'unset !important',
      }"
      centered
      :tabBarGutter="120"
    >
      <a-tab-pane key="1" :tab="$t('user.login.tab-login-credentials')">
        <a-alert
          v-if="isLoginError"
          type="error"
          showIcon
          style="margin-bottom: 24px"
          :message="$t('user.login.message-invalid-credentials')"
        />
        <a-form-item name="username">
          <a-input
            v-model:value="formState.username"
            :placeholder="$t('user.login.username.placeholder')"
            size="large"
            type="text"
          >
            <template #prefix>
              <UserOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="password">
          <a-input-password
            v-model:value="formState.password"
            :placeholder="$t('user.login.password.placeholder')"
            size="large"
          >
            <template #prefix>
              <LockOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input-password>
        </a-form-item>
      </a-tab-pane>
      <a-tab-pane key="2" :tab="$t('user.login.tab-login-mobile')">
        <a-form-item name="mobile">
          <a-input
            v-model:value="formState.mobile"
            size="large"
            type="text"
            :placeholder="$t('user.login.mobile.placeholder')"
          >
            <template #prefix>
              <PhoneOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input>
        </a-form-item>

        <a-row :gutter="16">
          <a-col class="gutter-row" :span="16">
            <a-form-item name="captcha">
              <a-input
                v-model:value="formState.captcha"
                size="large"
                type="text"
                :placeholder="
                  $t('user.login.mobile.verification-code.placeholder')
                "
              >
                <template #prefix>
                  <MailOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-button
              class="getCaptcha"
              tabindex="-1"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              size="large"
            >
              {{
                (!state.smsSendBtn &&
                  $t('user.register.get-verification-code')) ||
                state.time + ' s'
              }}
            </a-button>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>

    <a-form-item>
      <a-form-item name="remember" no-style>
        <a-checkbox v-model:checked="formState.remember">
          {{ $t('user.login.remember-me') }}
        </a-checkbox>
      </a-form-item>
      <a class="login-form-forgot" href="">
        {{ $t('user.login.forgot-password') }}
      </a>
    </a-form-item>

    <a-form-item>
      <a-button
        :disabled="disabled"
        type="primary"
        html-type="submit"
        class="login-form-button"
        :loading="loading"
      >
        {{ $t('user.login.login') }}
      </a-button>
      <a class="register">{{ $t('user.login.signup') }}</a>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { reactive, computed, ref } from 'vue';
import { notification } from 'ant-design-vue';
import {
  UserOutlined,
  LockOutlined,
  PhoneOutlined,
  MailOutlined,
} from '@ant-design/icons-vue';
import type { FormState, State } from './type';
import type { loginResponseData } from '@/api/user/type';
import { reqLogin } from '@/api/user';
import i18n from '@/lang';
import { getTimeState } from '@/utils';
import { useUserStore } from '@/store/modules/user';
import { useRouter } from 'vue-router';
const router = useRouter();
const userStore = useUserStore();
// 定义校验规则
const rules = computed(() => {
  return {
    username: [
      {
        required: true,
        message: i18n.global.t('user.userName.required'),
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        message: i18n.global.t('user.password.required'),
        trigger: 'blur',
      },
      {
        required: true,
        min: 6,
        max: 10,
        message: i18n.global.t('user.register.password.placeholder'),
        trigger: 'change',
      },
    ],
    mobile: [
      {
        required: true,
        pattern: /^1\d{10}$/,
        message: i18n.global.t('user.phone-number.required'),
      },
    ],
    captcha: [
      {
        required: true,
        message: i18n.global.t('user.verification-code.required'),
      },
    ],
  };
});

//表单数据
const formState = reactive<FormState>({
  username: '',
  password: '',
  mobile: '',
  captcha: '',
  remember: true,
});
// 状态管理
const loading = ref(false);
const isLoginError = ref(false);
const state = ref<State>({
  smsSendBtn: false,
  time: 60,
});
// 获取验证码
const getCaptcha = () => {
  // 这里可以添加获取验证码的逻辑
  state.value.smsSendBtn = true;
  let timer = setInterval(() => {
    if (state.value.time > 0) {
      state.value.time--;
    } else {
      clearInterval(timer);
      state.value.smsSendBtn = false;
      state.value.time = 60;
    }
  }, 1000);
};

//提交表单成功
let formRef = ref(null);
const onFinish = async (values: FormState) => {
  // console.log('Success:', values);
  loading.value = true;
  try {
    await userStore.userlogin({
      username: values.username,
      password: values.password,
    });
    router.push('/');
    notification['success']({
      message: i18n.global.t('user.login.success'),
      description: `${getTimeState()}，欢迎回来！`,
      duration: 4,
    });
  } catch (error) {
    // 用户名或密码错误，更新表单错误信息
    isLoginError.value = true;
    setTimeout(() => {
      isLoginError.value = false;
    }, 5000);
    // notification['error']({
    //   message: '错误',
    //   description: (error as Error).message,
    //   duration: 4
    // })
  } finally {
    loading.value = false;
  }
};

//提交表单失败
const onFinishFailed = (errorInfo: any) => {
  notification['error']({
    message: i18n.global.t('user.login.error'),
    description:
      ((errorInfo.response || {}).data || {}).message ||
      '请求出现错误，请稍后再试',
    duration: 4,
  });
};

//用户没有输入时禁用
const disabled = computed(() => {
  return !(formState.username && formState.password);
});

const activeKey = ref('1');
</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
